﻿using System;
using System.Collections.Generic;

using System.Text;
using HZ.DrugTrade.Model;
using HZ.Common;

namespace HZ.DrugTrade.BLL
{
    [Serializable]
    /// <summary>
    /// 消息系统实现
    /// </summary>
    public class BLL_Message : MarshalByRefObject, IBLL.IBLL_Message
    {

        #region IBLL_Message Members
        /// <summary>
        /// 向客户端广播消息
        /// </summary>
        /// <param name="message"></param>
        public void BroadCastMessage(string message)
        {
            if (BroadCastEvent != null)
            {
                HZ.DrugTrade.IBLL.BroadCastEventHandler tempEvent = null;

                int index = 1; //记录事件订阅者委托的索引，为方便标识，从1开始。
                foreach (Delegate del in BroadCastEvent.GetInvocationList())
                {
                    try
                    {
                        tempEvent = (HZ.DrugTrade.IBLL.BroadCastEventHandler)del;
                        tempEvent(message);
                    }
                    catch
                    {
                        // 客户端非法关闭，消息订阅取消。
                        BroadCastEvent -= tempEvent;
                    }
                    index++;
                }
            }
            else
            {
                // 没有客户端消息发送，当前无在线客户端。
            }
        }

        public event HZ.DrugTrade.IBLL.BroadCastEventHandler BroadCastEvent;

        #endregion



        #region 通知公告
           

        /// <summary>
        /// 发送通知消息
        /// 粒度到角色
        /// (比如 收信人为医疗机构/企业/地区招标中心)
        /// </summary>
        /// <param name="notice"></param>
        /// <returns></returns>
        public int AddNotice_Batch(IList<Notice> notices)
        {
            foreach (var item in notices)
            {
                ThrowHelper.Throw(item.NoticeSerialID != null, "item.NoticeSerialID != null");
                ThrowHelper.Throw(item.Title != null, "item.Title != null");
                ThrowHelper.Throw(item.NoticeContent != null, "iitem.NoticeContent  != null");
                item.PostUser = BLL_UserSession.GetCurrentUser().UserID;
                item.Sender = BLL_UserSession.GetCurrentUser().Org.OrgID;
                item.SendTime = DateTime.Now;

            }
            return DAL.DAL_Message.AddNotice_Batch(notices);
        }

        /// <summary>
        /// 获取已发布的公告
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.View.Notice> GetNotice(Model.Query.Notice where, int currentpage, int pagesize, out int totalrecord)
        {
            where.AuditStatus = true;
            where.Sender = BLL_UserSession.GetCurrentUser().Org.OrgID;
            return DAL.DAL_Message.GetAuditNotice(where, currentpage, pagesize, out totalrecord); 

        }

        /// <summary>
        /// 获取已接收的公告
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.View.Notice> GetRecievedNotice(Model.Query.Notice where, int currentpage, int pagesize, out int totalrecord)
        {
            where.AuditStatus = true;
            where.Reciever = BLL_UserSession.GetCurrentUser().UserRole.RoleID;
            return HZ.DrugTrade.DAL2.DAL_Helper.GetPagedView<Model.View.Notice, Model.Query.Notice>(where, currentpage, pagesize, out totalrecord);

        }

        /// <summary>
        /// 获取待审核的公告
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.View.Notice> GetAuditNotice(Model.Query.Notice where, int currentpage, int pagesize, out int totalrecord)
        {
            where.AuditStatus = false;
            where.Sender = BLL_UserSession.GetCurrentUser().Org.OrgID;
            //庄金冬修改
            //return HZ.DrugTrade.DAL2.DAL_Helper.GetPagedView<Model.View.Notice, Model.Query.Notice>(where, currentpage, pagesize, out totalrecord);
            return DAL.DAL_Message.GetAuditNotice(where, currentpage, pagesize, out totalrecord);          
        }

        /// <summary>
        /// 审核并修改公告
        /// </summary>
        /// <param name="notice"></param>
        /// <returns></returns>
        public int UpdateNotice_Audit(Notice notice)
        {
            ThrowHelper.Throw(notice.NoticeSerialID != null, "notice.NoticeSerialID != null");
            ThrowHelper.Throw(notice.AuditStatus != null, "notice.AuditStatus != null");
            notice.AuditUser = BLL_UserSession.GetCurrentUser().UserID;
            return HZ.Data.DAL_Helper.OperateTableSQL(notice, HZ.Data.TableOperator.Update);
        }

        /// <summary>
        /// 批量删除公告
        /// </summary>
        /// <param name="notices"></param>
        /// <returns></returns>
        public int DeleteNotice_Batch(IList<Notice> notices)
        {
            ThrowHelper.Throw(notices != null, "Notice不能为空！");
            foreach (var item in notices)
            {                
              ThrowHelper.Throw(!string.IsNullOrEmpty(item.NoticeSerialID), "NoticeSerialID为必需");
            }
            return DAL.DAL_Message.DeleteNotice_Batch(notices);
        }

        #endregion

        #region 消息
        /// <summary>
        /// 批量添加消息并存到发件箱
        /// (消息粒度到机构到机构只有主用户或主用户授权用户才能够发送消息)
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public int AddMessage_Save_Batch(IList<Message> message)
        {
            foreach (var item in message)
            {
                ThrowHelper.Throw(item.MessageID != null);
                ThrowHelper.Throw(item.Reciever != null);
                item.Sender = BLL_UserSession.GetCurrentUser().Org.OrgID;
                item.SendTime = DateTime.Now;
            }
            return DAL.DAL_Message.AddMessage_Save_Batch(message);

        }


        /// <summary>
        /// 批量发送消息
        /// (消息粒度到机构到机构只有主用户或主用户授权用户才能够发送消息)
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public int AddMessage_Batch(IList<Message> message)
        {
            foreach (var item in message)
            {
                ThrowHelper.Throw(item.MessageID != null);
                ThrowHelper.Throw(item.Reciever != null);
                item.Sender = BLL_UserSession.GetCurrentUser().Org.OrgID;
                item.SendTime = DateTime.Now;
            }
            return DAL.DAL_Message.AddMessage_Batch(message);

        }


        /// <summary>
        /// 批量删除消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public int DeleteMessage_Batch(IList<Message> message)
        {
            foreach (var item in message)
            {

                ThrowHelper.Throw(item.MessageID != null, "message.MessageID != null");
            }
            return DAL.DAL_Message.DeleteMessage_Batch(message);
        }

        /// <summary>
        /// 修改消息(修改后消息会变成未读状态，发送时间也重新刷新)
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public int UpdateMessage(Message message)
        {
            ThrowHelper.Throw(message.Status != null);
            return DAL.DAL_Message.UpdateMessage(message);

        }

        /// <summary>
        /// 获取消息[已收信息]
        /// (机构ID无需传入)
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.View.Message> GetMessage(Model.Query.Message where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL.DAL_Message.GetMessage(where, BLL_UserSession.GetCurrentUser().Org.OrgID, currentpage, pagesize, out totalrecord);

        }

       
        /// <summary>
        /// 获取已经发送的消息
        /// (机构ID无需传入)
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.View.Message> GetMessageSent(Model.Query.Message where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL.DAL_Message.GetMessageSent(where, BLL_UserSession.GetCurrentUser().Org.OrgID, currentpage, pagesize, out totalrecord);
        }

        #endregion

        #region 意见反馈
        /// <summary>
        /// 增加一个反馈
        /// </summary>
        /// <param name="feedback"></param>
        /// <returns></returns>
        public int AddFeedBack(FeedBack feedback)
        {

            return DAL.DAL_Message.AddFeedBack(feedback);
        }


         /// <summary>
        /// 批量增加反馈
        /// </summary>
        /// <param name="feedbackList"></param>
        /// <returns></returns>
        public int AddFeedBack_Batch(IList<FeedBack> feedbackList)
        {
            return DAL.DAL_Message.AddFeedBack_Batch(feedbackList);
        }

        /// <summary>
        /// 批量删除反馈
        /// </summary>
        /// <param name="feedbackList"></param>
        /// <returns></returns>
        public int DeleteFeedBack_Batch(IList<FeedBack> feedbackList)
        {
            ThrowHelper.Throw(feedbackList != null, "NoticeFeedBack！");
            foreach (var item in feedbackList)
            {
                ThrowHelper.Throw(!string.IsNullOrEmpty(item.FeedBackID), "NoticeFeedBack为必需");
            }
            return DAL.DAL_Message.DeleteFeedBack_Batch(feedbackList);
        }

        /// <summary>
        /// 回复一个反馈
        /// </summary>
        /// <param name="feedback"></param>
        /// <returns></returns>
        public int ReplyFeedBack(FeedBack feedback)
        {
            return DAL.DAL_Message.ReplyFeedBack(feedback);
        }
        /// <summary>
        /// 刷新反馈状态(已阅读等)
        /// </summary>
        /// <param name="feedback"></param>
        /// <returns></returns>
        public int UpdateFeedBack_Status(FeedBack feedback)
        {
            return DAL.DAL_Message.UpdateFeedBack_Status(feedback);

        }
        /// <summary>
        /// 察看反馈信息(中心端)
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.View.FeedBack> GetFeedBack_Manager(Model.Query.FeedBack where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL.DAL_Message.GetFeedBack_Manager(where, BLL_UserSession.GetCurrentUser().Org.OrgID, currentpage, pagesize, out totalrecord);

        }
        /// <summary>
        /// 察看反馈信息(发送端(医疗机构企业))
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public IList<Model.View.FeedBack> GetFeedBack_Sender(Model.Query.FeedBack where, int currentpage, int pagesize, out int totalrecord)
        {

            return DAL.DAL_Message.GetFeedBack_Sender(where, BLL_UserSession.GetCurrentUser().Org.OrgID, currentpage, pagesize, out totalrecord);

        }
        #endregion


        #region 预警功能
        /// <summary>
        /// 获取当前预警信息
        /// </summary>
        /// <param name="orgid"></param>
        /// <returns></returns>
        public IList<Model.View.WarningResult> GetWarning(string orgid)
        {
            List<Model.View.WarningResult> result = new List<HZ.DrugTrade.Model.View.WarningResult>();
            //IList<Model.Warning> warnings = HZ.Data.DAL_Helper.CommonFillList<Model.Warning>(HZ.Data.DbHelperFactory.Create().ExecuteTable(string.Format("SELECT * FROM TB_Warning WHERE OrgID = '{0}'", orgid)));

            IList<Model.Warning> warnings = HZ.Data.DAL_Helper.CommonFillList<Model.Warning>(HZ.Data.DbHelperFactory.Create().ExecuteTable(string.Format("SELECT * FROM TB_Warning ")));


            // 分析预警信息.
            HZ.Data.IDbHelper h =  HZ.Data.DbHelperFactory.Create();
            string i = "0";
            if (orgid.StartsWith("QH", StringComparison.CurrentCultureIgnoreCase)) // 医疗机构
            {
                // 增加默认值
                if (warnings.Count == 0)
                {
                    warnings.Add(new Warning()
                    {
                        OrgID = orgid,
                        IsUsing = true,
                        OrgType = 0,
                        WarningTime = 0,
                        WarningType = 0
                    });
                    warnings.Add(new Warning()
                    {
                        OrgID = orgid,
                        IsUsing = true,
                        OrgType = 0,
                        WarningTime = 0,
                        WarningType = 3
                    });
                    warnings.Add(new Warning()
                    {
                        OrgID = orgid,
                        IsUsing = true,
                        OrgType = 0,
                        WarningTime = 0,
                        WarningType = 5
                    });
                    //warnings.Add(new Warning()
                    //{
                    //    OrgID = orgid,
                    //    IsUsing = true,
                    //    OrgType = 0,
                    //    WarningTime = 0,
                    //    WarningType = 8
                    //});
                }

                foreach (var item in warnings)
                {
                    i = "0";
                    // 如果未启用则跳过
                    if (item.IsUsing != null && !item.IsUsing.Value)
                    {
                        continue;
                    }
                    HospitalWarning hwtype = (HospitalWarning)item.WarningType;
                    DateTime Dtime = item.WarningTime.GetValueOrDefault(0) == 0 ? DateTime.Now : DateTime.Now.AddDays(-1 * item.WarningTime.GetValueOrDefault(0));
                    switch (hwtype)
                    {
                        case HospitalWarning.建单未提交:
                            i = h.ExecuteScalar(string.Format(@"SELECT COUNT(*) FROM TB_PurchaseOrder
WHERE HospitalID = '{0}' AND OrderStatus = 0 AND PlanTime <= to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                            break;
                        case HospitalWarning.配送未验收:
                            i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM View_Distribution WHERE HospitalID = '{0}' AND WarehouseTime IS NULL AND DistributeTime <to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                            break;
                        //case HospitalWarning.开票未回款:
                        //    //SELECT COUNT(*) FROM View_Invoice AS vi WHERE InvoicePaySerialID IS NULL AND HospitalID = '{0}' AND InvoiceTime <= '{1}'
                        //    i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM View_Invoice vi WHERE AuditStatus='1' and InvoicePaySerialID IS NULL AND HospitalID = '{0}' AND InvoiceTime <= to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                        //    break;
                        default:
                            break;
                    }
                    if (!string.IsNullOrEmpty(i)&&int.Parse(i.ToString()) > 0)
                    {
                        result.Add(new HZ.DrugTrade.Model.View.WarningResult() { OrgID = orgid, WarningMessage = i.ToString(), WarningType = item.WarningType });
                    }
                   
                }

            }
            else
            {
                // 增加默认值
                if (warnings.Count == 0)
                {
                    //warnings.Add(new Warning()
                    //{
                    //    OrgID = orgid,
                    //    IsUsing = true,
                    //    OrgType = 0,
                    //    WarningTime = 0,
                    //    WarningType = 1
                    //});
                    warnings.Add(new Warning()
                    {
                        OrgID = orgid,
                        IsUsing = true,
                        OrgType = 0,
                        WarningTime = 0,
                        WarningType = 2
                    });
                    warnings.Add(new Warning()
                    {
                        OrgID = orgid,
                        IsUsing = true,
                        OrgType = 0,
                        WarningTime = 0,
                        WarningType = 4
                    });
                    //warnings.Add(new Warning()
                    //{
                    //    OrgID = orgid,
                    //    IsUsing = true,
                    //    OrgType = 0,
                    //    WarningTime = 0,
                    //    WarningType = 6
                    //});
                    warnings.Add(new Warning()
                    {
                        OrgID = orgid,
                        IsUsing = true,
                        OrgType = 0,
                        WarningTime = 0,
                        WarningType = 7
                    });
                }
                foreach (var item in warnings)
                {
                    i = "0";
                    // 如果未启用则跳过
                    if (item.IsUsing != null && !item.IsUsing.Value)
                    {
                        continue;
                    }
                    CompanyWarning cwtype = (CompanyWarning)item.WarningType;
                    DateTime Dtime = item.WarningTime.GetValueOrDefault(0) == 0 ? DateTime.Now : DateTime.Now.AddDays(-1 * item.WarningTime.GetValueOrDefault(0));

                    switch (cwtype)
                    {
                        //case CompanyWarning.提交未确认:
                        //    i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM View_PurchaseOrderDetail WHERE OrderDetailState = 1 AND CompanyID_PS = '{0}' AND StartTime <= to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                        //    break;
                        case CompanyWarning.确认未配送:
                            //i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM View_Distribution vd WHERE OrderDetailState = 2 AND DistributeTime IS NULL AND CompanyID_PS = '{0}' AND ExecuteTime <= to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                            i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM View_Distribution vd WHERE OrderDetailState = 1  AND CompanyID_PS = '{0}' AND ExecuteTime <= to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                            break;
                        case CompanyWarning.入库未开票:
                            i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM View_Distribution WHERE IsInvoice = 0 AND Dis_WarehouseCount > 0 AND CompanyID_PS = '{0}' AND WarehouseTime <= to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                            break;
                        //case CompanyWarning.回款未确认:
                        //    i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM View_InvoicePay WHERE InvoiceSerialID IS NOT NULL AND CompanyID_PS = '{0}' AND PayStatus = 0 AND InvoicePayTime <= to_date('{1}','yyyy-mm-dd hh24:Mi:ss')", item.OrgID, Dtime)).ToString();
                        //    break;
                        case CompanyWarning.退货未确认:
                            i = h.ExecuteScalar(string.Format("SELECT COUNT(*) FROM TB_ReturnMerchandiseDetail WHERE CompanyID = '{0}' AND ReturnState = 0 and returnserialid in (select returnserialid from TB_ReturnMerchandise where returnorderStatus=2)", item.OrgID)).ToString();
                            break;
                        default:
                            break;
                    }
                    if (!string.IsNullOrEmpty(i) && int.Parse(i.ToString()) > 0)
                    {
                        result.Add(new HZ.DrugTrade.Model.View.WarningResult() { OrgID = orgid, WarningMessage = i.ToString(), WarningType = item.WarningType });
                    }

                }

            }
            return result;

            throw new NotImplementedException();
        }

        /// <summary>
        /// 批量增加警告
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int AddWarning(IList<Warning> list)
        {
            foreach (var item in list)
            {

                ThrowHelper.Throw(item.OrgID != null);
            }
            return DAL.DAL_Warning.AddWarning(list);

        }

        /// <summary>
        /// 批量修改警告
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int UpadateWarning(IList<Warning> list)
        {
            foreach (var item in list)
            {
                ThrowHelper.Throw(item.OrgID != null);
            }

            return DAL.DAL_Warning.UpadateWarning(list);
        }

        /// <summary>
        /// 获取当前组织的预警设置
        /// </summary>
        /// <returns></returns>
        public IList<Warning> GetWarnigSettings()
        {
            string orgid = BLL_UserSession.GetCurrentUser().Org.OrgID;
            return DAL.DAL_Warning.GetWarnigSettings(orgid);
        }

        #endregion
    }


}
